//
//  XWHearingChartBrevityLineChartView.swift
//  XiaoweHearingAid
//
//  Created by edy on 2025/9/28.
//

import UIKit
import Charts
import Kingfisher

// 简洁的听力折线图
class XWHearingChartBrevityLineChartView: AppLineChartView {
    
    lazy var yAxisDescriptionLb = UILabel()
    lazy var xAxisDescriptionLb = UILabel()
    
    lazy var freqBandList: [Int] = WDRCModule.standardHearingChartFreqBandList
    
    var hcChartImageRadio: CGFloat = 1
    var hcChartLineWidth: CGFloat = 2
    
    var volumeUnitText: String {
        "dB"
    }
    var acLabelText: String {
        R.string.localizable.气导AC()
    }
    var bcLabelText: String {
        R.string.localizable.骨导BC()
    }
    
    var axisDescriptionLbHeight: CGFloat {
        10
    }
    var axisDescriptionLbWidth: CGFloat {
        124
    }

    override func addSubViews() {
        super.addSubViews()
        
        addSubview(yAxisDescriptionLb)
        addSubview(xAxisDescriptionLb)
                
//        layer.cornerRadius = 16
//        layer.backgroundColor = collectionBgColor.cgColor
        
        configAxisDescriptionLb(yAxisDescriptionLb)
        configAxisDescriptionLb(xAxisDescriptionLb)
        yAxisDescriptionLb.textAlignment = .left
        xAxisDescriptionLb.textAlignment = .right

        yAxisDescriptionLb.text = R.string.localizable.听阈DBHL()
        xAxisDescriptionLb.text = R.string.localizable.频率Hz()
    }
    
    func configAxisDescriptionLb(_ lb: UILabel) {
        lb.font = AppFont.harmonyOSSans(ofSize: 10, weight: .regular)
        lb.textAlignment = .left
        lb.textColor = majorTextColor
    }
    
//    func configHearingLossLevelLb(_ lb: UILabel) {
//        let font = AppFont.harmonyOSSans(ofSize: 14, weight: .regular)
//        lb.font = font
//        lb.textColor =  majorTextColor
//        lb.textAlignment = .center
//        lb.adjustsFontSizeToFitWidth = true
//    }
    
    override func relayoutSubViews() {
        yAxisDescriptionLb.snp.makeConstraints { make in
            make.height.equalTo(axisDescriptionLbHeight)
            make.width.lessThanOrEqualTo(axisDescriptionLbWidth)
            make.left.equalToSuperview().inset(10)
            make.top.equalToSuperview()
        }
        xAxisDescriptionLb.snp.makeConstraints { make in
            make.right.equalToSuperview().inset(8)
            make.width.lessThanOrEqualTo(axisDescriptionLbWidth)
            make.height.equalTo(axisDescriptionLbHeight)
            make.bottom.equalToSuperview()
        }
        
        chartView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
            make.top.equalTo(yAxisDescriptionLb.snp.bottom)
            make.bottom.equalTo(xAxisDescriptionLb.snp.top)
        }
    }
    
    func updateChart(isLeft: Bool, chartDetailModel: XWHAHearingChartDetailModel) {
        var acItems: [XWHAOFFreqPuretoneInputItemModel] = []
        var bcItems: [XWHAOFFreqPuretoneInputItemModel] = []
        
        if isLeft {
            acItems = chartDetailModel.airLeftRes
            if acItems.isEmpty {
                acItems = chartDetailModel.acLeftResToInputItemList
            }
            
            bcItems = chartDetailModel.boneLeftRes
        } else {
            acItems = chartDetailModel.airRightRes
            
            if acItems.isEmpty {
                acItems = chartDetailModel.acRightResToInputItemList
            }
            
            bcItems = chartDetailModel.boneRightRes
        }
        
        updateChart(isLeft: isLeft, acFreqBandList: acItems, bcFreqBandList: bcItems)
    }
    
    func updateChart(isLeft: Bool, pureToneTestInput: XWHAOFFreqPuretoneInputModel) {
        var acItems: [XWHAOFFreqPuretoneInputItemModel] = []
        var bcItems: [XWHAOFFreqPuretoneInputItemModel] = []
        
        if isLeft {
            acItems = pureToneTestInput.air.left
            bcItems = pureToneTestInput.bone.left
        } else {
            acItems = pureToneTestInput.air.right
            bcItems = pureToneTestInput.bone.right
        }
        
        updateChart(isLeft: isLeft, acFreqBandList: acItems, bcFreqBandList: bcItems)
    }
    
    func updateChart(isLeft: Bool, acFreqBandList: [XWHAOFFreqPuretoneInputItemModel], bcFreqBandList: [XWHAOFFreqPuretoneInputItemModel]) {
        var lineColor: UIColor
        var markerBg: UIImage?
        
        var chartTipIconName: String = ""
        
        var acItems: [XWHAOFFreqPuretoneInputItemModel] = []
        var bcItems: [XWHAOFFreqPuretoneInputItemModel] = []
        if isLeft {
            lineColor = UIColor(hex: 0x007EFF)!
//            iconView.image = R.image.left_ear_chart_tip_icon()
            
            chartTipIconName = "left_ear_chart_tip_icon"

            
//            markerBg = R.image.left_chart_marker_bg()

            markerBg = R.image.left_chart_wdrc_marker_bg()
        } else {
            lineColor = UIColor(hex: 0xFF5D34)!
            
            chartTipIconName = "right_ear_chart_tip_icon"
            
//            markerBg = R.image.right_chart_marker_bg()
            markerBg = R.image.right_chart_wdrc_marker_bg()
        }
        
        let lang = AppFunctionHelper.getLocalPrimaryLanguage()
        if lang != "zh" {
            chartTipIconName += "_en"
        }
        
//        iconView.image = UIImage(named: chartTipIconName)
        markerView.image = markerBg
        
        acItems = acFreqBandList
        bcItems = bcFreqBandList
        
        acItems.removeAll(where: { $0.value <= XWHAFrequencyBandRecordModel.invalidValue && $0.hasScreen })
        bcItems.removeAll(where: { $0.value <= XWHAFrequencyBandRecordModel.invalidValue && $0.hasScreen })
        
        acItems = acItems.sorted(by: \.freqBand)
        bcItems = bcItems.sorted(by: \.freqBand)
        
        freqBandList = acItems.map({ $0.freqBand })
        configXAxis()
                
//        let lossLevel = XWHAHearingChartDetailModel.getHearingLossLevel(freqBandRecordList: acItems)
//        hearingLossLevelLb.text = lossLevel.description
        
        var acDataEntries = [ChartDataEntry]()
        for (_, iItem) in acItems.enumerated() {
            if let tIndex = freqBandList.firstIndex(where: { $0 == iItem.freqBand }) {
                let value = getValue(isLeft: isLeft, isAC: true, itemModel: iItem)
                let entry = ChartDataEntry.init(x: Double(tIndex), y: value)
                entry.icon = getImage(isLeft: isLeft, isAC: true, itemModel: iItem)
                acDataEntries.append(entry)
            }
        }
        
        var bcDataEntries = [ChartDataEntry]()
        for (_, iItem) in bcItems.enumerated() {
            if let tIndex = freqBandList.firstIndex(where: { $0 == iItem.freqBand }) {
                let value = getValue(isLeft: isLeft, isAC: true, itemModel: iItem)
                let entry = ChartDataEntry.init(x: Double(tIndex), y: value)
                entry.icon = getImage(isLeft: isLeft, isAC: false, itemModel: iItem)
                bcDataEntries.append(entry)
            }
        }
        
        let acChartDataSet = LineChartDataSet(entries: acDataEntries, label: acLabelText)
        config(chartDataSet: acChartDataSet, lineColor: lineColor)
        acChartDataSet.lineWidth = hcChartLineWidth
        
        var dataSets: [LineChartDataSet] = []
        dataSets.append(acChartDataSet)
        
        if !bcDataEntries.isEmpty {
            let bcChartDataSet = LineChartDataSet(entries: bcDataEntries, label: bcLabelText)
            config(chartDataSet: bcChartDataSet, lineColor: lineColor)
            bcChartDataSet.lineWidth = hcChartLineWidth
            dataSets.append(bcChartDataSet)
        }
        
        //目前折线图只包括1根折线
        let chartData = LineChartData(dataSets: dataSets)
        
        //设置折现图数据
        chartView.data = chartData
    }
    
    private func getValue(isLeft: Bool, isAC: Bool, itemModel: XWHAOFFreqPuretoneInputItemModel) -> Double {
        if itemModel.value <= XWHAFrequencyBandRecordModel.invalidValue {
            return 120
        }
        return itemModel.value
    }
    private func getImage(isLeft: Bool, isAC: Bool, itemModel: XWHAOFFreqPuretoneInputItemModel) -> UIImage? {
        var tImage: UIImage?
        
        
        if isAC { // 气导
            if isLeft { // 左
                if itemModel.hasScreen { // 掩蔽
                    if itemModel.hasReact { // 有反应
                        tImage = R.image.ac_mask_l_icon()
                    } else { // 无反应
                        tImage = R.image.ac_mask_no_response_l_icon()
                    }
                } else { // 未掩蔽
                    if itemModel.hasReact { // 有反应
                        tImage = R.image.ac_no_mask_l_icon()
                    } else { // 无反应
                        tImage = R.image.ac_no_response_l_icon()
                    }
                }
            } else { // 右
                if itemModel.hasScreen { // 掩蔽
                    if itemModel.hasReact { // 有反应
                        tImage = R.image.ac_mask_r_icon()
                    } else { // 无反应
                        tImage = R.image.ac_mask_no_response_r_icon()
                    }
                } else { // 未掩蔽
                    if itemModel.hasReact { // 有反应
                        tImage = R.image.ac_no_mask_r_icon()
                    } else { // 无反应
                        tImage = R.image.ac_no_response_r_icon()
                    }
                }
            }
        } else { // 骨导
            if isLeft { // 左
                if itemModel.hasScreen { // 掩蔽
                    if itemModel.hasReact { // 有反应
                        tImage = R.image.bc_mask_l_icon()
                    } else { // 无反应
                        tImage = R.image.bc_mask_no_response_l_icon()
                    }
                } else { // 未掩蔽
                    if itemModel.hasReact { // 有反应
                        tImage = R.image.bc_no_mask_l_icon()
                    } else { // 无反应
                        tImage = R.image.bc_no_response_l_icon()
                    }
                }
            } else { // 右
                if itemModel.hasScreen { // 掩蔽
                    if itemModel.hasReact { // 有反应
                        tImage = R.image.bc_mask_r_icon()
                    } else { // 无反应
                        tImage = R.image.bc_mask_no_response_r_icon()
                    }
                } else { // 未掩蔽
                    if itemModel.hasReact { // 有反应
                        tImage = R.image.bc_no_mask_r_icon()
                    } else { // 无反应
                        tImage = R.image.bc_no_response_r_icon()
                    }
                }
            }
        }
        if hcChartLineWidth == 1 {
            return tImage
        } else {
            var resize = tImage?.size ?? .zero
            resize = resize * hcChartImageRadio
            let retImage = tImage?.kf.resize(to: resize)
            return retImage
        }
    }
    
    private func config(chartDataSet: LineChartDataSet, lineColor: UIColor) {
        //        chartDataSet.highlightEnabled = false
        chartDataSet.drawVerticalHighlightIndicatorEnabled = false
        chartDataSet.drawHorizontalHighlightIndicatorEnabled = false
        chartDataSet.drawValuesEnabled = false
        chartDataSet.drawCirclesEnabled = false
        chartDataSet.drawCircleHoleEnabled = false
        chartDataSet.mode = .linear
        chartDataSet.setColor(lineColor)
        
        //开启填充色绘制
        chartDataSet.drawFilledEnabled = false
//        let gradientColors = [lineColor.cgColor, UIColor.white.cgColor] as CFArray
//        //每组颜色所在位置（范围0~1)
//        let colorLocations:[CGFloat] = [1.0, 0.0]
//        //生成渐变色
//        if let gradient = CGGradient.init(colorsSpace: CGColorSpaceCreateDeviceRGB(),
//                                          colors: gradientColors, locations: colorLocations) {
//            //将渐变色作为填充对象s
//            chartDataSet.fill = Fill.fillWithLinearGradient(gradient, angle: 90)
//            chartDataSet.fillFormatter = DefaultFillFormatter(block: { dataSet, dataProvider in
//                CGFloat(self.chartView.leftAxis.axisMaximum)
//            })
//        }
    }

}

extension XWHearingChartBrevityLineChartView {
    
    override func configXAxis() {
        chartView.xAxis.labelPosition = .bottom
        
        let xMaxValue = freqBandList.count - 1
        chartView.xAxis.axisMaxLabels = xMaxValue + 1
        
        chartView.xAxis.axisMinimum = 0
        chartView.xAxis.granularity = 1
        chartView.xAxis.axisMaximum = Double(xMaxValue)
        
        chartView.xAxis.labelCount = chartView.xAxis.axisMaxLabels
        chartView.xAxis.forceLabelsEnabled = true
//        chartView.xAxis.granularityEnabled = true
        
        chartView.xAxis.axisLineWidth = 1
        chartView.xAxis.axisLineColor = UIColor.black.withAlphaComponent(0.05)
        chartView.xAxis.drawAxisLineEnabled = true
        
        chartView.xAxis.gridLineWidth = 1
        chartView.xAxis.gridColor = UIColor.black.withAlphaComponent(0.05)
        chartView.xAxis.drawGridLinesEnabled = true
        
        chartView.xAxis.labelFont = AppFont.harmonyOSSans(ofSize: 10)
        chartView.xAxis.labelTextColor = minorTextColor
        chartView.xAxis.valueFormatter = DefaultAxisValueFormatter(block: { [weak self] value, _ in
            let x = value.int
            var ret = x.string
            guard let self = self else {
                return ret
            }
            
            ret = self.getXValue(xIndex: x)
            
            return ret
        })
    }
    
    func getXValue(xIndex: Int) -> String {
        var ret = xIndex.string
        if xIndex < self.freqBandList.count, xIndex >= 0 {
            let tBand = self.freqBandList[xIndex]
            if tBand >= 1000 {
                let tValue1 = tBand.double / 1000
                let tValue2 = tBand % 1000
                if tValue2 == 0 {
                    ret = "\(tValue1.int)k"
                } else {
                    ret = "\(tValue1)k"
                }
            } else {
                ret = tBand.string
            }
        }
        
        return ret
    }
    
}

// MARK: - ChartViewDelegate
extension XWHearingChartBrevityLineChartView {
    
    override func chartValueSelected(_ chartView: ChartViewBase, entry: ChartDataEntry, highlight: Highlight) {
        guard let dataSet = chartView.data?.dataSets[highlight.dataSetIndex] else { return }
        
        //        markerView.setShowOffset(chartView, entry: entry, highlight: highlight)
        ////        let entryIndex = dataSet.entryIndex(entry: entry)
        //        markerView.textLb.text =  .string
        //        markerView.detailLb.text = entry.y.int.string
        
        let x = entry.x.int
        let y = entry.y.int
        
        let ret = getXValue(xIndex: x)
        
        var title = ""
        if let dLabel = dataSet.label {
            title = dLabel + "\n"
        }
        markerView.setLabel("\(title)\(ret)Hz/\(y.string)\(volumeUnitText)")
    }
    
}
